import type { Options, Column, Record } from "./type"
import Insert from './insert'
import { watch, onMounted, onBeforeUnmount } from 'vue';

export default class extends Insert {
    constructor(options: Options){
        super(options)

        const keypressDelete = () => this.keypressDelete()

        onMounted(() => {
            document.addEventListener('keydown', keypressDelete)
        })
        onBeforeUnmount(() => {
            document.removeEventListener('keydown', keypressDelete)
        })
    }

    // 删除行
    async deleteRows() {
        if (this.props.customEditer?.onEditBefore){
            await this.props.customEditer?.onEditBefore?.(this.selectAreasData.value, this);
        }

        if(this.props.openUndo && this.emptyHistoryRecord()) this.addHistoryRecord();

        if (this.selectedState.rows?.length) {
            this.selectedState.rows.sort((a, b) => b - a)
            this.selectedState.rows.forEach(rowindex => {
                this.dataSource.value.splice(rowindex, 1)
            })
            this.selectedState.rows = undefined
        } else if (this.selectedState.cells?.length){
            const rows = Array.from(new Set(this.selectedState.cells.map(v => v[0])))
            rows.sort((a, b) => b - a)
            rows.forEach(rowindex => {
                this.dataSource.value.splice(rowindex, 1)
            })
            this.selectedState.cells = undefined
        } else {
            this.dataSource.value.splice(this.getMinStartY(), this.getMaxEndY() - this.getMinStartY() + 1)
            this.selectedState.startY = this.selectedState.endY = undefined
            this.selectedState.endX = this.selectedState.startX = undefined 
        }
        

        if(this.props.customEditer?.onRemove) {
            this.props.customEditer?.onRemove?.()
        }

        if(this.props.openUndo) this.addHistoryRecord();
    }

    // 删除单元格
    private async deleteCells() {
        if (this.props.customEditer?.onEditBefore){
            await this.props.customEditer?.onEditBefore?.(this.selectAreasData.value, this);
        }
        
        if(this.props.openUndo && this.emptyHistoryRecord()) this.addHistoryRecord();

        let clearRecord:null|{
            newValue: any,
            oldValue: any,
            column: Column,
            record: Record
        }[] = null
        if (this.props.customEditer?.onClear) clearRecord = [];

        if (this.selectedState.cells?.length) {
            this.selectedState.cells.forEach(([rowindex, colindex]) => {
                // -1 表头
                if (rowindex === -1) return;

                const dataIndex = this.columns.value[colindex].dataIndex
                if (clearRecord) {
                    clearRecord.push({
                        newValue: undefined,
                        oldValue: this.getValueByModel(dataIndex, this.dataSource.value[rowindex]),
                        column: this.columns.value[colindex],
                        record: this.dataSource.value[rowindex]
                    })
                }
                
                this.tryValidateCell?.(rowindex, colindex, "change");
                this.setValueByModel(dataIndex, this.dataSource.value[rowindex], undefined)
                
            })
        } else {
            let startRow = this.getMinStartY()
            let startCol = this.getMinStartX()
            while(startRow <= this.getMaxEndY()){
                while(startCol <= this.getMaxEndX()){
                    const dataIndex = this.columns.value[startCol].dataIndex
                    if (clearRecord) {
                        clearRecord.push({
                            newValue: undefined,
                            oldValue: this.getValueByModel(dataIndex, this.dataSource.value[startRow]),
                            column: this.columns.value[startCol],
                            record: this.dataSource.value[startRow]
                        })
                    }

                    this.tryValidateCell?.(startRow, startCol, "change");
                    this.setValueByModel(dataIndex, this.dataSource.value[startRow], undefined)
                    startCol++
                }
                startCol = this.getMinStartX();
                startRow++;
            }
        }

        if(clearRecord && this.props.customEditer?.onClear) {
            this.props.customEditer?.onClear(clearRecord)
        }

        if(this.props.openUndo) this.addHistoryRecord();

    }
    private keypressDelete() {
        if (!this.currentView) return;
        if (this.checkHasReadonly(this.selectAreasData.value.records)) return;
        if (this.checkHasDisable(this.selectAreasData.value.records)) return;
        
        const isInputActive = document.activeElement?.tagName === 'INPUT' || document.activeElement?.tagName === 'TEXTAREA';
        const isInputInfo = isInputActive ? document.activeElement?.getBoundingClientRect() : {};
        if (isInputActive && isInputInfo?.height > 0) return;
        
        if (event.keyCode == 46 || event.keyCode == 8) {
            if(this.selectedState.startX === -1 || this.selectedState.rows?.length) this.deleteRows();
            else if(this.selectedState.startX !== undefined || this.selectedState.cells?.length) this.deleteCells()
            return false;
        }
    }
}